<template>
  <div class="kw-accordion">
    <slot></slot>
  </div>
</template>

<script>
  export default {
    name: 'kw-accordion',
    componentName: 'KwAccordion',
    props: {
      value: {
        type: [Array, String, Number],
        default() {
          return [];
        }
      }
    },
    data() {
      return {
        activeNames: [].concat(this.value)
      }
    },
    created() {
      this.$on('item-click', this.handleItemClick);
    },
    watch: {
      value(value) {
        this.activeNames = [].concat(value);
      }
    },
    methods: {
      setActiveNames(activeNames) {
        activeNames = [].concat(activeNames);
        this.activeNames = activeNames;
        this.$emit('input', this.activeNames);
        this.$emit('change', this.activeNames);
      },
      handleItemClick(item) {
        let activeNames = this.activeNames.slice(0);
        let index = activeNames.indexOf(item.name);

        if (index > -1) {
          activeNames.splice(index, 1);
        } else {
          activeNames.push(item.name);
        }
        this.setActiveNames(activeNames);
      }
    }
  }
</script>

<style lang="less">
  .kw-accordion {
    display:flex;
    flex-direction: column;
    .accordion-title {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      height: 50px;
      line-height: 50px;
      font-size: 16px;
      background: #eee;
      text-indent: 1em;
      cursor: pointer;
      .iconfont {
        width: 20px;
        margin-right: 15px;
      }
    }
    .accordion-list {
      list-style: none;
      padding: 0;
      margin: 0;
      font-size: 16px;
      overflow: hidden;
      max-height: 0;
      transition: max-height .5s ease-out;
      &.maxHeight {
        max-height: 500px;
        transition: max-height .5s ease-in;
      }
      .accordion-item {
        display: flex;
        align-items: baseline;
        height: 50px;
        line-height: 50px;
        font-size: 16px;
        text-indent: 1em;
        cursor: pointer;
      }
    }
  }
</style>